const gulp = require("gulp");
const sass = require('gulp-sass');
const rename = require("gulp-rename");
const through = require('through2');




function appendWxss(urls) {
  let str = "";
  if (Object.prototype.toString.call(urls) == "[object Array]" && urls.length) {
    str = urls.join("")
  } else {
    str = str;
  }
  if (!str) {
    return stream;
  } else {
    str = Buffer.from(str);
    // 创建一个 stream 通道，以让每个文件通过
    var stream = through.obj(function (file, enc, cb) {
      if (file.isStream()) {
        return cb();
      } else if (file.isBuffer()) {
        file.contents = Buffer.concat([str, file.contents]);
      }
      // 确保文件进入下一个 gulp 插件
      this.push(file);
      // 告诉 stream 引擎，我们已经处理完了这个文件
      cb();
    });
    return stream;
  }
}



const appSassPaths = ['./scss/index.scss'];
const commonSassPaths = ['./scss/*.scss'];
const pageSassPaths = ['./pages/**/*.{scss,sass}'];
const customComponentSassPaths = ['./customComponent/**/*.{scss,sass}']
const componentSassPaths = ['./components/**/*.{scss,sass}']

function appSass() {
  return gulp.src(appSassPaths)
    .pipe(sass({
      outputStyle: 'compressed'
    }).on('error', sass.logError))
    .pipe(rename({
      basename: "index",
      extname: ".wxss"
    }))
    .pipe(gulp.dest('./'))
}


function pagesSass() {
  return gulp.src(pageSassPaths)
    .pipe(sass({
      outputStyle: 'compressed'
    }).on('error', sass.logError))
    .pipe(appendWxss(['@import "../../index.wxss";']))
    .pipe(rename({
      basename: "index",
      extname: ".wxss"
    }))
    .pipe(gulp.dest('./pages/'))
}






function customComponentSass() {
  return gulp.src(customComponentSassPaths)
    .pipe(sass({
      outputStyle: 'compressed'
    }).on('error', sass.logError))
    .pipe(appendWxss(['@import "../../index.wxss";']))
    .pipe(rename({
      basename: "index",
      extname: ".wxss"
    }))
    .pipe(gulp.dest('./customComponent/'))
}


function componentSass() {
  return gulp.src(componentSassPaths)
    .pipe(sass({
      outputStyle: 'compressed'
    }).on('error', sass.logError))
    .pipe(appendWxss(['@import "../../index.wxss";']))
    .pipe(rename({
      basename: "index",
      extname: ".wxss"
    }))
    .pipe(gulp.dest('./components/'))
}






function watchs() {
  gulp.watch([...appSassPaths, ...pageSassPaths, ...customComponentSassPaths,...componentSassPaths,...commonSassPaths], gulp.series(appSass, pagesSass, customComponentSass,componentSass));


}


gulp.task('default', gulp.parallel(appSass, pagesSass, customComponentSass,componentSass,watchs));